<?php
namespace app\controller\admin;

use app\BaseController;
use think\facade\Request;
use app\model\SlideInfoModel;
use app\model\SlideModel;
use think\Exception;
use think\Image;
class Slide extends BaseController
{

    public function index(){

        $list = SlideModel::page( 1 )->select();
        return json( $list );

    }

    public function single(){

        $id = $_GET['id'];

        $info = SlideModel::where( 'id', $id )->find();
        $info['picture_list'] = SlideInfoModel::where( 'slide_id', $info->id )->select();


        return json( $info ) ;
    }


    public function remove( Request $request ){

        $res= [
            'code'=>0,
        ];

        $id = Request::param( 'id' );

        if( empty( $id ) ){

            $res= [
                'code'=>1,
                'message'=>'请选中你要删除的项',
            ];
            return json( $res );

            
        }

        $res['ret'] = SlideModel::where( 'id', $id )->delete();

        $res['ret_info'] = SlideInfoModel::where( 'slide_id', $id )->delete();
        

        return json( $res );

    }


    public function edit(){

        $id = Request::param( 'id' );

        $title = Request::param( 'title' );
        $name = Request::param( 'name' );
        $desc = Request::param( 'desc' );
        $status = Request::param( 'status' );

        $res['code'] = 0;
        $data = [
            'title'      => $title,
            'name'      => $name,
            'desc'      => $desc,
            'status'    => $status,
        ];
        //todo 修改 nav

        if( $id ){
            $res['ret'] = SlideModel::update(  $data,[ 'id' => $id ] );
        }else{
            // $data['created_at'] = date('Y-m-d H:i:s');
            // $data['updated_at'] = date('Y-m-d H:i:s');
            $res['ret'] = SlideModel::create( $data );
            $id = $res['ret']->id;
        }
        
        $res['id'] = $id;

        // todo 保存 轮播图 图片列表
        SlideInfoModel::where('slide_id', $id )->delete();
        $picture_list = $_POST['picture_list'];
        if( !empty($picture_list ) ){

            $picture_list = is_array($picture_list) ? $picture_list : json_decode($picture_list, true);

            foreach( $picture_list as $item ){

                SlideInfoModel::create([

                    'slide_id'  => $id,
                    'src'       => $item['src'],
                    'sort_order'=> $item['sort_order'],
                ]);
            }
        }

        return json( $res );

    }

}